package anno

import (
	"encoding/json"
	"fmt"
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/gox/osx/filex"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"gitee.com/zhongguo168a/gocodes/myx/logx"
	"github.com/codeskyblue/go-sh"
	"github.com/spf13/cobra"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"wails/cmds/maketools"
)

func init() {
	startCmd := &cobra.Command{
		Use:   "rsync-frame",
		Short: "构建",
		Run: func(cmd *cobra.Command, args []string) {
			rsync()
		},
	}

	maketools.RootCmd.AddCommand(startCmd)
}

func GetFileConfigAllMap() (map[string]map[string]interface{}, []error) {
	配置文件路径 := "d:/mycodes/yxeditor/client-config-cocos/build"
	files := filex.NewFilter().
		IncludeSuffix(".ycj").
		IgnoreDir(配置文件路径 + "/config/recycle").
		IgnoreDir(配置文件路径 + "/config/world/场景").
		GetFileInfosByPath(配置文件路径 + "/config")

	return GetFileConfig(配置文件路径, files)
}

func GetFileConfig(配置文件路径 string, files []filex.IFileInfo) (map[string]map[string]interface{}, []error) {
	var list = map[string]map[string]interface{}{}
	var errs []error
	for _, info := range files {
		if info.Path() == "." {
			continue
		}

		path := func() (x string) {
			x = info.Path()
			return x
		}()
		path = filepath.ToSlash(path)

		bcontent, err := os.ReadFile(info.Path())
		m := map[string]interface{}{}
		if err != nil {
			errs = append(errs, errorx.Wrap(err, "read file", datax.M{path: info.Path()}))
			continue
		}
		err = json.Unmarshal(bcontent, &m)
		if err != nil {
			errs = append(errs, errorx.Wrap(err, "unmarshal json", datax.M{path: info.Path()}))
			continue
		}
		configPath := strings.Replace(path, 配置文件路径+"/", "", 1)
		for _, val := range m {
			config := val.(map[string]interface{})
			config["_file"] = configPath
		}

		list[configPath] = m

	}

	return list, errs
}

func textpacker() {
	files := filex.NewFilter().
		IncludeSuffix(".png", ".tps").
		ExcludeAllDir().
		IgnoreDir("D:/assets/effects/_downloads").
		IgnoreDir("D:/assets/effects/帧动画/_export").
		GetFileInfosByPath("D:/assets/effects/帧动画")

	pngdirs := map[string]int{}
	tpsdirs := map[string]string{}
	for _, info := range files {
		ext := filepath.Ext(info.Path())
		dir := filepath.ToSlash(filepath.Dir(info.Path()))
		if ext == ".png" {
			pngdirs[dir]++
		} else if ext == ".tps" {
			tpsdirs[dir] = info.Path()
		}
	}

	// 删除掉包含tps的目录
	//for dir, _ := range pngdirs {
	//	if tpsdirs[dir] != "" {
	//		pngdirs[dir] = 0
	//	}
	//}

	exportBasePath := `D:/assets/effects/帧动画/_export`
	for dir, count := range pngdirs {
		if count > 0 {
			相对路径 := strings.ReplaceAll(dir, "D:/assets/effects/帧动画/", "")
			pathArr := strings.Split(相对路径, "/")
			帧动画名称 := pathArr[len(pathArr)-1]
			pathArr = pathArr[:len(pathArr)-1]
			相对输出路径 := strings.Join(pathArr, "/")
			输出路径 := exportBasePath + "/" + 相对输出路径
			os.MkdirAll(输出路径, os.ModePerm)
			sheetPath := 输出路径 + "/" + 帧动画名称

			cmd := fmt.Sprintf(`TexturePacker --format json --sheet "%v.png" --data "%v.atlas" "%v"`, sheetPath, sheetPath, dir)
			gocmd := exec.Command("CMD")
			//  核心点,直接修改执行命令方式
			gocmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: fmt.Sprintf(`/c %s`, cmd), HideWindow: true}
			gocmd.Stdout = os.Stdout
			gocmd.Stderr = os.Stderr
			err := gocmd.Run()
			if err != nil {
				fmt.Println(err)
			}
		}
	}

	//for dir, tpsPath := range tpsdirs {
	//	相对路径 := strings.ReplaceAll(dir, "D:/assets/effects/帧动画/", "")
	//	pathArr := strings.Split(相对路径, "/")
	//	帧动画名称 := pathArr[len(pathArr)-1]
	//	pathArr = pathArr[:len(pathArr)-1]
	//	相对输出路径 := strings.Join(pathArr, "/")
	//	输出路径 := exportBasePath + "/" + 相对输出路径
	//	os.MkdirAll(输出路径, os.ModePerm)
	//	sheetPath := 输出路径 + "/" + 帧动画名称
	//	cmd := fmt.Sprintf(`TexturePacker "%v" --format json --sheet "%v.png" --data "%v.json" "%v"`, tpsPath, sheetPath, sheetPath, dir)
	//	gocmd := exec.Command("CMD", "/C", cmd)
	//	gocmd.Stdout = os.Stdout
	//	gocmd.Stderr = os.Stderr
	//	err := gocmd.Run()
	//	fmt.Println(err)
	//}

}

func rsync() {
	cmd := sh.NewSession()
	cmd.ShowCMD = true
	//clientPath + "/assets/resources/project/debug_config.json"
	var err error
	{
		err = cmd.Command("/bin/sh", "-c",
			fmt.Sprintf(`rsync -avr %v %v`,
				"D:/assets/effects/帧动画/_export",
				"D:/mycodes/yxeditor/client-game-cocos/assets/assets/bundles/extends/帧动画",
			)).Run()
		if err != nil {
			logx.Error(err)
		}
	}
}
